package com.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.device.domain.Region;
import com.device.mapper.RegionMapper;
import com.device.service.IRegionService;
import com.share.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {


    @Autowired
    private RegionMapper regionMapper;

    /**
     * 根据上级code获取下级数据列表
     */
    @Override
    public List<Region> treeSelect(String parentCode) {
        List<Region> list = list(new LambdaQueryWrapper<Region>().eq(Region::getParentCode, parentCode));
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                long count = count(new LambdaQueryWrapper<Region>().eq(Region::getParentCode, item.getCode()));
                item.setHasChildren(count > 0);
            });
        }
        return list;
    }


    /**
     * 根据地区编码获取名称
     */
    @Override
    public String getNameByCode(String code) {
        if (StringUtils.isEmpty(code)) {
            return "";
        }
        Region region = getOne(new LambdaQueryWrapper<Region>().eq(Region::getCode, code).select(Region::getName));
        if (null != region) {
            return region.getName();
        }
        return "";
    }
}
